/*
*  路由拦截器, 用于判断拦截替换页面
* */
import store from '../store'
import NProgress from 'nprogress'

const 登陆验证 = async (to, from, next) => {
  const toHome = () => {
    next({path: '/', replace: true})
    NProgress.done()
  }
  const toLogin = () => {
    next({name: 'login', replace: true})
    NProgress.done()
  }
  if (store.getters.userInfo) { // 已经登陆
    if (to.name === 'login') {
      toHome()
    } else {
      next()
    }
  } else if (to.name !== 'login') { // 没有登陆
    try {
      // 尝试拉取用户信息,无则跳转到登陆页
      await store.dispatch('GetInfo')
      next()
    } catch (err) {
      await store.dispatch('FedLogOut')
      // Message.error(err.message || '登陆验证失败,请重新登陆')
      toLogin()
      throw err
    }
  } else {
    next()
  }
}


const arr = [登陆验证]

async function interceptor(router) {
  arr.forEach(x => router.beforeEach(x))
}

export default interceptor
